//
//  YZLHomePageViewController.m
//  Car
//
//  Created by dllo on 15/10/28.
//  Copyright © 2015年 岳明. All rights reserved.
//

#import "YZLHomePageViewController.h"
#import "Macro.h"
#import "HTTPTOOL.h"
#import "YZLHomePageModel.h"
#import "YZLFocusImgs.h"
#import "YZLFocusListModel.h"
#import "YZLNewsListModel.h"
#import "YZLHomePageCell.h"
#import "YZLtakeOkView.h"
#import "YZLListView.h"
#import "YZLNewsLinkViewController.h"
#import "YZLSeachViewController.h"

@interface YZLHomePageViewController ()<UIScrollViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, yzlListViewDelegate, YZLHomePageCellDelegate>

@property (nonatomic, strong) UICollectionView *collectionView; /**< 内容 */
@property (nonatomic, strong) UIScrollView *scrollView; /**< 标签 */
@property (nonatomic, strong) UIButton *button; /**< 下拉控件 */
@property (nonatomic, strong) NSArray *tagArray; /**< 标签数组 */
@property (nonatomic, strong) NSArray *tagShowArray; /**< 显示的标签数组 */
@property (nonatomic, strong) NSArray *tagHideArray; /**< 隐藏的标签数组 */
@property (nonatomic, strong) UIView *lineView; /**< 标签滑动的线 */
@property (nonatomic, strong) NSMutableArray *modelArray; /**< 装model数组 */
@property (nonatomic, strong) YZLtakeOkView *takeOkView; /**< 下拉列表-已经订阅 */
@property (nonatomic, strong) YZLListView *listView; /**< 下拉列表 */

@end

@implementation YZLHomePageViewController

#pragma mark - 本地数据解析 tagArray
- (void)handlData {
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"tagArray.plist"];

        /* 判断文件是否存在 */
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            /* 存在则导出 */
            self.tagArray = [NSArray arrayWithContentsOfFile:path];
        } else {
            /* 不存在则写入 */
            self.tagArray = @[
                              @{
                                  @"title":@"最新",
                                  @"frist":@"a",
                                  @"last":@"6.0/getNewsList",
                                  @"type":@"1"
                                  },
                              @{
                                  @"title":@"新闻",
                                  @"frist":@"a",
                                  @"last":@"6.0/getNewsList",
                                  @"type":@"2"
                                  },
                              @{
                                  @"title":@"测评",
                                  @"frist":@"a",
                                  @"last":@"6.0/getNewsList",
                                  @"type":@"3"
                                  },
                              @{
                                  @"title":@"导购",
                                  @"frist":@"a",
                                  @"last":@"6.0/getNewsList",
                                  @"type":@"4"
                                  },
                              @{
                                  @"title":@"油价变动",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"1"
                                  },
                              @{
                                  @"title":@"车辆召回",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"2"
                                  },
                              @{
                                  @"title":@"新车上市",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"3"
                                  },
                              @{
                                  @"title":@"新技术",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"4"
                                  },
                              @{
                                  @"title":@"新能源车",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"6"
                                  },
                              @{
                                  @"title":@"新车谍照",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"8"
                                  },
                              @{
                                  @"title":@"多车对比",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"20"
                                  },
                              @{
                                  @"title":@"对比选车",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"28"
                                  },
                              @{
                                  @"title":@"激情赛车",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"33"
                                  },
                              @{
                                  @"title":@"汽车音响",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"985"
                                  },
                              @{
                                  @"title":@"奇闻车市",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"1540"
                                  },
                              @{
                                  @"title":@"概念车",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"18534"
                                  },
                              @{
                                  @"title":@"SUV对比",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"76392"
                                  },
                              @{
                                  @"title":@"购车技巧",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"76395"
                                  },
                              @{
                                  @"title":@"改装升级",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"83757"
                                  },
                              @{
                                  @"title":@"视频",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"144998"
                                  },
                              @{
                                  @"title":@"旅行游记",
                                  @"frist":@"mi",
                                  @"last":@"xcarapp/getdingyue",
                                  @"type":@"154980"
                                  },
                              @{@"sum":@"5"}
                              ];
            [self.tagArray writeToFile:path atomically:YES];
        }

//    }
//    return self;
}

#pragma mark - 创建标签滑动 scrollView
- (void)createScrollView {
    //关闭自适应
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.scrollView = [[UIScrollView alloc] init];
    if (self.tagShowArray.count < 4) {
        self.scrollView.frame = CGRectMake(0, 64, self.tagShowArray.count *kWidth / 4, 40);
    } else self.scrollView.frame = CGRectMake(0, 64, kWidth - kWidth / 8, 40);
    
    //关闭水平指示器
    self.scrollView.showsHorizontalScrollIndicator = NO;
    // 内容视图范围
    self.scrollView.contentSize = CGSizeMake(self.tagShowArray.count * kWidth / 4, 0);
    
    // 标签
    [self createButtons];
    
    // 蓝色指示条
    self.lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 30, kWidth / 4, 5)];
    self.lineView.backgroundColor = [UIColor colorWithRed:124 / 255.f green:208 / 255.f blue:250 / 255.f alpha:1];
    [self.scrollView addSubview:self.lineView];
    
    
    
    [self.view addSubview:self.scrollView];
    self.scrollView.delegate = self;
    
}

#pragma mark - 创建滑动标签按键 button
- (void)createButtons {
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadScrollButton:) name:@"addTag" object:@"addArray"];
//    
    /**
     *  根据显示标签的数组设置标签按键的数量，并调用数组中的数据
     */
    for (int i = 0; i < self.tagShowArray.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(i * kWidth / 4, 0, kWidth / 4, 40);
        [button setTitle:[[self.tagShowArray objectAtIndex:i] objectForKey:@"title"] forState:UIControlStateNormal];
        
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [self.scrollView addSubview:button];
        [button addTarget:self action:@selector(tegButton:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 101 + i;
    }

}

#pragma mark - 点击标签事件
- (void)tegButton:(UIButton *)button {
 
    //点击标签 View 跟随
    self.lineView.frame = CGRectMake((button.tag - 101) * kWidth / 4, 38, kWidth / 4, 2.5);
    //点击标签选择相应的 collection
    self.collectionView.contentOffset = CGPointMake((button.tag - 101) * kWidth, 0);
    
    //改变scrollView 的偏移量，使选中的永远处在视图的第一个位置, 当scrollView 所的偏移的量小于等于 scrollView 的宽的时候，偏移量不变
    if (self.scrollView.contentSize.width - kWidth / 4 * (button.tag - 101) <= self.scrollView.frame.size.width) {
        self.scrollView.contentOffset = CGPointMake(self.scrollView.contentSize.width - self.scrollView.frame.size.width, 0);
    } else self.scrollView.contentOffset = CGPointMake((button.tag - 101) * kWidth / 4, 0);
}

#pragma mark - 创建下拉标签列表 button
- (void)createButton {
    self.button = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:self.button];
    self.button.frame = CGRectMake(kWidth - kWidth / 8, 64, kWidth / 8, 40);
    [self.button setImage:[UIImage imageNamed:@"xiala"] forState:UIControlStateNormal];
    [self.button addTarget:self action:@selector(xialaButton:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 点击下拉事件
- (void)xialaButton:(UIButton *)button {

    [UIView animateWithDuration:.35 animations:^{
        // scrollView 视图删除
//        [self.scrollView removeFromSuperview];
        self.scrollView.hidden = YES;
        // 下拉 button 隐藏
        self.button.alpha = 0.0;
        // 改变标签栏视图
        self.takeOkView.alpha = 1.0;
        // 改变下拉列表的 frame
        self.listView.frame = CGRectMake(0, 104, kWidth, kHeight - 104);
        self.listView.alpha = 1;
    }];
    
}

#pragma mark - 下拉列表
- (void)createXiaLaView {
    // 创建“已经订阅”视图
    self.takeOkView = [[YZLtakeOkView alloc] initWithFrame:CGRectMake(0, 64, kWidth, 40)];
    // 创建后隐藏
    self.takeOkView.alpha = 0;
    [self.view addSubview:self.takeOkView];
    [self.takeOkView.packUpButton addTarget:self action:@selector(packUpButton:) forControlEvents:UIControlEventTouchUpInside];
    // 创建“下拉列表”
    self.listView = [[YZLListView alloc] initWithFrame:CGRectMake(0, - kHeight - 208, kWidth, kHeight - 208)];
    [self.view addSubview:self.listView];
    // 创建后隐藏
    self.listView.alpha = 0;
    // 为显示的 collectionView 数组传值
    self.listView.showArray = self.tagShowArray;
    // 为隐藏的 collectionView 数组传值
    self.listView.hideArray = self.tagHideArray;
    self.listView.delegate = self;
}

#pragma mark - 下拉列表收起
- (void)packUpButton:(UIButton *)button {
    // 下拉列表收起时，创建 scrollView
    

    [UIView animateWithDuration:.35 animations:^{
        // 改变标签栏视图
        // scrollView 显示
        self.scrollView.hidden = NO;

        self.takeOkView.alpha = 0.0;
        self.button.alpha = 1.0;
        self.listView.frame = CGRectMake(0, -kHeight - 208, kWidth, kHeight - 208);
        self.listView.alpha = 0;
    }];
    
}

#pragma mark - 点击已订阅事件
- (void)clickOnAddTagWithIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item != 0) { // 当点击的不是最新标签
        // 将显示的数组和隐藏的数组，赋给中间可变数组
        NSMutableArray *tempShowArray = [NSMutableArray arrayWithArray:self.tagShowArray];
        NSMutableArray *tempHideArray = [NSMutableArray arrayWithArray:self.tagHideArray];
        // 判断点击标签的 Item，并将该 Item 对应显示数组中的元素删除
        [tempShowArray removeObjectAtIndex:indexPath.item];
        // 将删除的元素添加到隐藏的数组中
        [tempHideArray addObject:[self.tagShowArray objectAtIndex:indexPath.item]];
        // 取出改变的显示数组长度，写到字典中
        NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
        [tempDic setObject:[NSString stringWithFormat:@"%ld", tempShowArray.count] forKey:@"sum"];
        // 将改变后的数组添加到一个总数组中
        NSMutableArray *tempArray = [NSMutableArray array];
        [tempArray addObjectsFromArray:tempShowArray];
        [tempArray addObjectsFromArray:tempHideArray];
        [tempArray addObject:tempDic];
        
        // 修改本地文件
        NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"tagArray.plist"];
        [tempArray writeToFile:path atomically:YES];
        
        // 重新加载数据
        [self handlData];
        [self handleArray];

        [self.scrollView removeFromSuperview];
        
        [self.collectionView reloadData];
        [self createScrollView];
        self.scrollView.hidden = YES;
        // 通知分别向显示和隐藏 collectionView 分别发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"addTag" object:@"addArray" userInfo:@{@"showArray":tempShowArray}];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"deleteTag" object:@"deleteArray" userInfo:@{@"hideArray":tempHideArray}];
    }
}

- (void)clickOnDeleteTagWithIndexPath:(NSIndexPath *)indexPath {
    // 将显示的数组和隐藏的数组，赋给中间可变数组
    NSMutableArray *tempShowArray = [NSMutableArray arrayWithArray:self.tagShowArray];
    NSMutableArray *tempHideArray = [NSMutableArray arrayWithArray:self.tagHideArray];
    
    // 判断点击标签的 Item，并将该 Item 对应隐藏数组中的元素删除
    [tempHideArray removeObjectAtIndex:indexPath.item];
    // 将删除的元素添加到显示的数组中
    [tempShowArray addObject:[self.tagHideArray objectAtIndex:indexPath.item]];
    // 取出改变的显示数组长度，写到字典中
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
    [tempDic setObject:[NSString stringWithFormat:@"%ld", tempShowArray.count] forKey:@"sum"];
    // 将改变后的数组添加到一个总数组中
    NSMutableArray *tempArray = [NSMutableArray array];
    [tempArray addObjectsFromArray:tempShowArray];
    [tempArray addObjectsFromArray:tempHideArray];
    [tempArray addObject:tempDic];
    
    // 修改本地文件
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"tagArray.plist"];
    [tempArray writeToFile:path atomically:YES];
    // 重新加载数据
    [self handlData];
    [self handleArray];
    
    [self.collectionView reloadData];
    
    [self.collectionView reloadData];
    [self createScrollView];
    self.scrollView.hidden = YES;
    
    // 通知分别向显示和隐藏 collectionView 分别发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"addTag" object:@"addArray" userInfo:@{@"showArray":tempShowArray}];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"deleteTag" object:@"deleteArray" userInfo:@{@"hideArray":tempHideArray}];
}

#pragma mark - 创建主视图 collectionView
- (void)createCollectionView {
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flow.itemSize = CGSizeMake(kWidth, kHeight - 150);
    flow.minimumLineSpacing = 0;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 104, kWidth, kHeight - 150) collectionViewLayout:flow];
    [self.view addSubview:self.collectionView];
    self.collectionView.pagingEnabled = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    // 重定池
    [self.collectionView registerClass:[YZLHomePageCell class] forCellWithReuseIdentifier:@"firstReuse"];
    
    // 监视 collectionView 的改变，改变 scrollView
    [self.collectionView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:@"abc"];
}

#pragma mark - 监视器
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    // 获取 collectionView 的偏移量
    CGPoint point = [[change objectForKey:@"new"] CGPointValue];
    // 获取不同 Item 时的变化情况
    for (int i = 0; i < self.tagShowArray.count; i++) {
        // 当 Item 改变时
        if (point.x == i * kWidth) {
            // 指示蓝线随 button 改变
            self.lineView.frame = CGRectMake(i * kWidth / 4, 38, kWidth / 4, 2.5);
            // scrollView 改变偏移量
            self.scrollView.contentOffset = CGPointMake(i * kWidth / 4, 0);
            //改变scrollView 的偏移量，使选中的永远处在视图的第一个位置, 当scrollView 所的偏移的量小于等于 scrollView 的宽的时候，偏移量不变
            if (self.scrollView.contentSize.width - kWidth * i / 4 <= self.scrollView.frame.size.width) {
                self.scrollView.contentOffset = CGPointMake(self.scrollView.contentSize.width - self.scrollView.frame.size.width, 0);
            }
            
        }
    }
}

#pragma mark - Item 的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.tagShowArray.count;
}

#pragma mark - collectionView 传值
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
    YZLHomePageCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"firstReuse" forIndexPath:indexPath];
    cell.urlDic = [self.tagShowArray objectAtIndex:indexPath.item];
    cell.isZero = indexPath.item;
    cell.delegate = self;
    return cell;
}

#pragma mark - 标签分组
- (void)handleArray {
    //取出文件中的显示的标签个数
    NSInteger tagShowNum = [[[self.tagArray lastObject] objectForKey:@"sum"] integerValue];
    
    
    //取出显示的数组内容
    NSMutableArray *mTagShowArr = [NSMutableArray array];
    
    for (int i = 0; i < tagShowNum; i++) {
        [mTagShowArr addObject:[self.tagArray objectAtIndex:i]];
    }
    self.tagShowArray = mTagShowArr;
    
    //取出隐藏的数组内容
    NSMutableArray *mTagHideArr = [NSMutableArray array];
    for (NSInteger i = tagShowNum; i < self.tagArray.count - 1; i++) {
        [mTagHideArr addObject:[self.tagArray objectAtIndex:i]];
    }
    self.tagHideArray = mTagHideArr;
    
   

}

#pragma mark - 推出新闻详情界面
- (void)pushNewsListDetailsWithString:(NSString *)newsLink withType:(NSString *)type{
    YZLNewsLinkViewController *nlVC = [[YZLNewsLinkViewController alloc] init];
    nlVC.urlString = newsLink;
    nlVC.typeString = type;
    [self.navigationController pushViewController:nlVC animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.modelArray = [NSMutableArray array];
    
    //bar颜色
    [self navigationbarColor];
    
    self.navigationItem.title = @"汽车资讯";
    
    // 右侧搜索 navigationItem
    UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"shouyezhuyetubiao05"] style:UIBarButtonItemStyleDone target:self action:@selector(searchButton:)];
    self.navigationItem.rightBarButtonItem = searchButton;
    
    [self handlData];
    [self handleArray];
    [self createCollectionView];
    [self createScrollView];
    [self createXiaLaView];
    [self createButton];
    
    
}

#pragma mark - 点击搜索事件 - 模态推出
- (void)searchButton:(UIBarButtonItem *)button {
    NSLog(@"让我们来搜索");
    YZLSeachViewController *sVC = [[YZLSeachViewController alloc] init];
    UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:sVC];
    [self presentViewController:navigation animated:YES completion:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
